import java.util.ArrayList;
import java.util.List;

public class StackOfPlates {

    private List<List<Integer>> lists;
    private int cap;

    public StackOfPlates(int cap) {
        lists = new ArrayList<>();
        this.cap = cap;
    }

    public void push(int val) {
        int size = lists.size();
        if(size == 0 || lists.get(size-1).size() >= cap){
            lists.add(new ArrayList<>());
            size++;
        }
        List<Integer> tmpList = lists.get(size-1);
        if(tmpList.size() < cap){
            tmpList.add(val);
        }
    }

    public int pop() {
        return popAt(lists.size()-1);
    }

    public int popAt(int index) {
        int size = lists.size();
        if(index >= size || index < 0){
            return -1;
        }
        List tmpList = lists.get(index);
        if(tmpList.isEmpty()){
            return -1;
        }
        int res = (Integer) tmpList.remove(tmpList.size()-1);
        if(tmpList.isEmpty()){
            lists.remove(index);
        }
        return res;
    }
}
